import 'dart:async';

import 'package:chathouse/pages/expert/wallet_page.dart';
import 'package:chathouse/pages/login/select_role_page.dart';
import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../constant/app_constant.dart';
import '../../model/expert.dart';
import '../../model/member_info.dart';
import '../../public/event_bus.dart';
import '../../push/chat_house_push.dart';
import '../../util/base_utils.dart';
import '../../util/log.dart';
import '../client/account/account_privacy_page.dart';
import '../client/account/contact_us.dart';
import '../client/account/update_pwd.dart';
import '../client/account/use_clause_page.dart';
import '../login/login_page.dart';
import '../login/privacy_page.dart';
import 'charts_page.dart';
import 'edit_Expert_page.dart';
import 'masterplate_page.dart';

class MinePage extends StatefulWidget {
  const MinePage({Key? key}) : super(key: key);

  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage>
    with AutomaticKeepAliveClientMixin, NavigationHelper {
  Expert? info;
  Expert? member;
  MemberInfo? _memberInfo;

  StreamSubscription? refreshSubscription;
  StreamSubscription? refreshSubscription2;

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    refreshSubscription?.cancel();
    refreshSubscription2?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    loadMemberInfo();
    loadBalance();

    getMembersInfo();

    refreshSubscription = eventBus.on<UpdateMemberInfo>().listen((event) {
      loadBalance();
      getMembersInfo();
    });

    refreshSubscription2 = eventBus.on<ToEditAccountEvent>().listen((event) {
      navigateTo(const EditExpertAccountPage());
    });
  }

  getMembersInfo() {
    Apis.getMembersInfo().then((value) {
      var jsonData = value?.data;
      _memberInfo = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);
      LogUtil.d("getMembersInfo success ");
      setState(() {});
    }).catchError((error) {
      LogUtil.d("getMembersInfo error");
    });
  }

  void loadMemberInfo() {
    Obj.showLoading();
    Apis.expertInfo()
        .then((response) => {
              Obj.dismissLoading(),
              setState(() {
                var data = response?.data["data"];
                info = Expert.fromJson(data);
                setState(() {});
              })
            })
        .onError((error, stackTrace) =>
            {Obj.dismissLoading(), print("bb"), print(error)});
  }

  void loadBalance() {
    Obj.showLoading();
    Apis.getMembersInfo()
        // ignore: avoid_print
        .then((response) => {
              Obj.dismissLoading(),
              setState(() {
                var data = response?.data["data"];
                member = Expert.fromJson(data);
                setState(() {});
              })
            })
        .onError((error, stackTrace) =>
            {Obj.dismissLoading(), print("bb"), print(error)});
  }

  static var textStyle =
      getTextStyle(24.sp, fontType: FontType.BOLD, color: Colors.black);

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        body: SafeArea(
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(top: Styles.magin_16),
            child: SizedBox(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Stack(
                    children: [
                      Text('歡迎回來',
                              style: getTextStyle(30.sp,
                                  fontType: FontType.BOLD, color: Colors.black))
                          .setContainer(
                              margin: EdgeInsets.only(left: Styles.magin_24)),
                      Text("${member?.membersName}",
                              style: getTextStyle(20.sp,
                                  fontType: FontType.BOLD, color: Colors.black))
                          .setContainer(
                              margin: EdgeInsets.only(
                                  left: Styles.magin_24, top: 50.w)),
                    ],
                  ),
                  (member?.memberImage ?? "").isEmpty
                      ? ImageUtils.image('assets/images/expert_avatar.png',
                              width: 80.w,
                              height: 80.w,
                              imageType: ImageType.ASSET,
                              radius: 40.w)
                          .setContainer(
                              margin: EdgeInsets.only(right: Styles.magin_24))
                      : ImageUtils.image(member?.memberImage ?? '',
                              width: 80.w,
                              height: 80.w,
                              imageType: ImageType.NETWORK,
                              radius: 40.w)
                          .setContainer(
                              margin: EdgeInsets.only(right: Styles.magin_24)),
                ],
              ),
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          Expanded(
            child: ListView(
              // itemExtent: 44,
              children: [
                MyContainer(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    height: 42.w,
                    child: InkWell(
                        onTap: () async {
                          //#todo 如果要回调刷新，用eventbus
                          navigateTo(const EditExpertAccountPage());
                        },
                        child:
                        // Text(
                        //   ">編輯檔案",
                        //   style: textStyle,
                        // )
                        MyText(
                          textStyle: textStyle, str: "編輯檔案", iconData: Icons.person, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                        )
                    ),
                  ),
                ),
                // Container(
                //   height: 42.w,
                //   child: InkWell(
                //     onTap: () {
                //       Get.to(const WealletPage());
                //     },
                //     child: Row(
                //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //       crossAxisAlignment: CrossAxisAlignment.center,
                //       children: [
                //         Text(
                //           ">服務開通",
                //           style: textStyle,
                //         ),
                //         Text(
                //           // ignore: unrelated_type_equality_checks
                //           (info?.balance?.toInt() == 0) ? "未開通" : "已開通",
                //           style: getTextStyle(24.sp,
                //               fontType: FontType.BOLD, color: Styles.mainColor),
                //         )
                //       ],
                //     ),
                //   ),
                // ),
                MyContainer(
                  child: Container(
                    height: 42.w,
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => {
                              Get.to(const Masterplate()),
                            },
                        child: MyText(
                            textStyle: textStyle, str: "報價單模本", iconData: Icons.assignment_outlined, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                        )
                    ),
                  ),
                ),
                InkWell(
                  onTap: () => {
                    eventBus.fire(UpdateRootIndexEvent(3)),
                  },
                  child: MyContainer(
                    child: Container(
                      height: 42.w,
                      alignment: Alignment.centerLeft,
                      child:
                      // Text(
                      //   ">服務通知",
                      //   style: textStyle,
                      // ),
                        MyText(
                          textStyle: textStyle, str: "服務通知", iconData: Icons.notifications, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                        )
                    ),
                  ),
                ),
                MyContainer(
                  child: Container(
                    height: 42.w,
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => {
                              Get.to(const ChartsPage()),
                            },
                        child:
                        // Text(
                        //   ">接單產量Chart",
                        //   style: textStyle,
                        // )
                      MyText(
                      textStyle: textStyle, str: "接單產量Chart", iconData: Icons.pie_chart , color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                    )
                    ),
                  ),
                ),
                MyContainer(
                  child: Container(
                    height: 42.w,
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => {
                              Get.defaultDialog(
                                  title: "確定轉到用戶版嗎？",
                                  textCancel: "取消",
                                  textConfirm: "確定",
                                  middleText: "",
                                  buttonColor: Colors.white,
                                  cancelTextColor: MyColors.black_0000011,
                                  confirmTextColor: MyColors.black_0000011,
                                  radius: 20.w,
                                  titlePadding: EdgeInsets.all(20.w),
                                  onConfirm: () {
                                    SpUtil.clear();
                                    Get.offAll(const SelectRolePage());
                                    SpUtil.putString(Keys.userRole, "b");
                                    AppConstant.userRole = UserRole.c;
                                    Get.to(LoginPage());
                                    //獲取token
                                    String token = SpUtil.getString(Keys.token);
                                    LogUtil.d("TOKEN: $token");
                                  },
                                  onCancel: () {
                                    Get.back();
                                  })
                            },
                        child:
                        // Text(
                        //   ">轉到用戶版",
                        //   style: textStyle,
                        // )
                      MyText(
                        textStyle: getTextStyle(24.sp, fontType: FontType.BOLD, color: Color(0xFFFEFBEA)), str: "轉到用戶版", iconData: Icons.switch_account, color: Color(0xFFFEFBEA), bgColor: Color(0xFFF19C38),
                      )
                    ),
                  ),
                ),
                MyContainer(
                  child: Container(
                    height: 42.w,
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => {Get.to(UpdatePwdPage(2))},
                        child:
                        // Text(
                        //   ">重設密碼",
                        //   style: textStyle,
                        // )
                        MyText(
                          textStyle: textStyle, str: "重設密碼", iconData: Icons.info_outline, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                        )
                    ),
                  ),
                ),
                MyContainer(
                  child: Container(
                    height: 42.w,
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => {Get.to(ContactUsPage(2))},
                        child:
                        // Text(
                        //   ">聯絡我們",
                        //   style: textStyle,
                        // )
                        MyText(
                          textStyle: textStyle, str: "聯絡我們", iconData: Icons.headphones, color: Color(0xFF74A3A8), bgColor: Color(0xFFD2F7B0),
                        )
                    ),
                  ),
                ),
                MyContainer(
                  child: Container(
                    height: 42.w,
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => Get.to(UseClausePage()),
                        child:
                        // Text(
                        //   ">平台使用條款",
                        //   style: textStyle,
                        // )
                        MyTextNoIcon(
                          textStyle: textStyle, str: "平台使用條款", bgColor: Color(0xFFC5D6AC),
                        )
                    ),
                  ),
                ),
                MyContainer(
                  child: Container(
                    height: 42.w,
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => {Get.to(ClientPrivacyPage())},
                        child:
                        // Text(
                        //   ">隱私政策聲明",
                        //   style: textStyle,
                        // )
                        MyTextNoIcon(
                          textStyle: textStyle, str: "隱私政策聲明", bgColor: Color(0xFFC5D6AC),
                        )
                    ),
                  ),
                ),
                MyContainer(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: InkWell(
                        onTap: () => {
                              Get.defaultDialog(
                                  title: "確定註銷賬號嗎？",
                                  textCancel: "取消",
                                  textConfirm: "確定",
                                  middleText: "",
                                  buttonColor: Colors.white,
                                  cancelTextColor: MyColors.black_0000011,
                                  confirmTextColor: MyColors.black_0000011,
                                  radius: 20.w,
                                  titlePadding: EdgeInsets.all(20.w),
                                  onConfirm: () {
                                    SpUtil.clear();
                                    //初始化極光
                                    ChatHousePush.instance.initPlatformState();
                                    Get.offAll(const SelectRolePage());
                                    Apis.deleteMember({
                                      "membersIds":
                                          _memberInfo?.data?.membersId.toString()
                                    })
                                        .then((value) => {
                                              ToastUtil.showToast("注销账号成功"),
                                            })
                                        .onError((error, stackTrace) => {
                                              ToastUtil.showToast("注销账号成功"),
                                            });
                                  },
                                  onCancel: () {
                                    Get.back();
                                  })
                            },
                        child:
                        Text(
                          "> 註銷賬號",
                          style: textStyle,
                        )
                      // MyText(
                      //   textStyle: textStyle, str: "註銷賬號", iconData: Icons.delete_forever , color: Color(0xFFF13638), bgColor: Color(0xFFD2F7B0),
                      // )
                    ),
                  ),
                ),
                Container(
                  height: 24,
                ),
                Container(
                  alignment: Alignment.center,
                  child: Container(
                    alignment: Alignment.center,
                    width: 140.w,
                    padding: REdgeInsets.symmetric(
                      vertical: 12.w,
                    ),
                    decoration: BoxDecoration(
                        color: Styles.mainColor,
                        borderRadius: BorderRadius.circular(100)),
                    child: Text(' 登  出 ',
                        style: getTextStyle(20.sp,
                            fontType: FontType.BOLD, color: Colors.white)),
                  ).setOnClickListener(() {
                    Get.defaultDialog(
                        title: "確定退出當前賬號嗎？",
                        textCancel: "取消",
                        textConfirm: "確定",
                        middleText: "",
                        buttonColor: Colors.white,
                        cancelTextColor: MyColors.black_0000011,
                        confirmTextColor: MyColors.black_0000011,
                        radius: 20.w,
                        onConfirm: () {
                          SpUtil.clear();
                          //初始化極光
                          ChatHousePush.instance.initPlatformState();
                          Get.offAll(const SelectRolePage());
                        },
                        onCancel: () {
                          Get.back();
                        });
                  }),
                ),
                Container(
                  height: 66.w,
                ),
              ],
              shrinkWrap: true,
              padding: const EdgeInsets.symmetric(horizontal: 24),
            ),
          ),
        ],
      ),
    ));
  }
}

class MyContainer extends StatelessWidget {
  const MyContainer({
    Key? key,
    required this.child,
  }) : super(key: key);

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 4, bottom: 4),
      child: child,
    );
  }
}

class MyText extends StatelessWidget {
  const MyText({
    Key? key,
    required this.textStyle, required this.str, required this.color, required this.bgColor, required this.iconData,
  }) : super(key: key);

  final TextStyle textStyle;
  final String str;
  final IconData iconData;
  final Color color;
  final Color bgColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width*0.6,
      ),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.all(
          Radius.circular(10),
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          children: [
            Expanded(
              child: Text(
                str,
                style: textStyle,
              ),
            ),
            Icon(
              iconData,
              color: color,
              size: 30.0,
            ),
          ],
        ),
      ),
    );
  }
}

class MyTextNoIcon extends StatelessWidget {
  const MyTextNoIcon({
    Key? key,
    required this.textStyle, required this.str, required this.bgColor,
  }) : super(key: key);

  final TextStyle textStyle;
  final String str;
  final Color bgColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        minHeight: 0, //minimum height
        minWidth: 0, // minimum width
        maxHeight: MediaQuery.of(context).size.height,
        //maximum height set to 100% of vertical height
        maxWidth: MediaQuery.of(context).size.width*0.6,
        //maximum width set to 100% of width
      ),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.all(
          Radius.circular(10),
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          children: [
            Expanded(
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  str,
                  style: textStyle,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}